<template>
  <a-spin :spinning="loading">
    <div style="height: 525px">
      <a-form :hide-required-mark="true" :form="form" layout="inline">
        <a-row>
          <a-col :span="8">
            <a-form-item style="width: 100%;height: 59px" :labelCol="labelCol" :wrapperCol="wrapperCol" label="车道名称">
              <a-input
                placeholder="请输入车道名称"
                v-decorator="['armName', {
                  rules: [{ required: true, message: '请输入车道名称' },{max:50,message:'车道名称被限制在50个字符以内'}]
                }]"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item style="width: 100%;height: 59px" :labelCol="labelCol" :wrapperCol="wrapperCol" label="设备序列号">
              <a-input
                placeholder="请输入设备序列号"
                v-decorator="['serialNo', {
                  rules: [{ required: true, message: '请输入设备序列号'},{max:20,message: '设备序列号被限制在20个字符以内'}]
                }]"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-row>
              <a-col :span="11">
                <a-form-item style="width: 100%;height: 59px" :labelCol="{xs: {span: 0},sm: {span: 0}}" :wrapperCol="{xs: {span: 24},sm: {span: 24}}">
                  <a-select
                    placeholder="源区域"
                    :options="areaIdOptions"
                    v-decorator="['sourceAreaId', {initialValue:''}]"/>
                </a-form-item>
              </a-col>
              <a-col :span="2" style="text-align: center">
                <a-form-item style="width: 100%;height: 59px" :labelCol="{xs: {span: 0},sm: {span: 0}}" :wrapperCol="{xs: {span: 24},sm: {span: 24}}">
                  <a-icon type="arrow-right" />
                </a-form-item>
              </a-col>
              <a-col :span="11">
                <a-form-item style="width: 100%;height: 59px" :labelCol="{xs: {span: 0},sm: {span: 0}}" :wrapperCol="{xs: {span: 24},sm: {span: 24}}">
                  <a-select
                    placeholder="目标区域"
                    :options="areaIdOptions"
                    v-decorator="['targetAreaId', {initialValue:''}]"/>
                </a-form-item>
              </a-col>
            </a-row>
          </a-col>

        </a-row>

        <a-row>
          <a-col :span="8">
            <a-form-item style="width: 100%;height: 59px" :labelCol="labelCol" :wrapperCol="wrapperCol" label="ip地址">
              <a-input
                placeholder="请输入ip地址"
                v-decorator="['ipAddr', {rules:[{required:true,pattern:'^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}$',message:'请输入正确的Ip地址'}]}]"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item style="width: 100%" :labelCol="labelCol" :wrapperCol="wrapperCol" label="出入口类型">
              <a-select v-decorator="['armType', {initialValue:'0'}]" placeholder="请选择出口类型">
                <a-select-option key="0" value="0">入口</a-select-option>
                <a-select-option key="1" value="1">出口</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item style="width: 100%" :labelCol="labelCol" :wrapperCol="{xs: {span: 16}, sm: {span: 16} ,style:'textAlign:left'}" label="是否启用">
              <a-radio-group v-decorator="['armStatus', {initialValue:1}]">
                <a-row>
                  <a-radio :value="1">启用</a-radio>
                  <a-radio :value="0" style="margin-left: 5px;">不启用</a-radio>
                </a-row>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="16">
          </a-col>
          <a-col :span="8" align="right">
            <a-button style="width:100px" type="primary" @click="onSubmit">添加</a-button>
          </a-col>
        </a-row>

      </a-form>
      <br/>
      <a-table
        :pagination="ipagination"
        :columns="columns"
        :dataSource="dataSource"
        bordered
        ref="table"
        :loading="loading"
        rowKey="id"
        style="height: 290px;margin-bottom: 25px;text-align: center"
        size="middle"
        @change="handleTableChange">

        <template v-for="col in [ 'armName','serialNo','ipAddr']" :slot="col" slot-scope="text, record">
          <div :key="col" >
            <a-input
              size="small"
              v-if="record.editable"
              :value="text"
              @change="e => handleChange(e.target.value, record.id, col)"/>
            <template v-else>{{ text }}</template>
          </div>
        </template>

        <span slot="rtspUrl" slot-scope="text,record">
          <div :title="text" :style="{maxWidth: '115px',whiteSpace: 'nowrap',textOverflow: 'ellipsis',overflow: 'hidden', wordWrap: 'break-word', wordBreak: 'break-all' }">
            <a-input
              size="small"
              v-if="record.editable"
              :value="text"
              @change="e => handleChange(e.target.value, record.id, 'rtspUrl')"/>
            <template v-else>{{ text }}</template>
          </div>
        </span>
        <span slot="videoUrl" slot-scope="text,record">
          <div :title="text" :style="{maxWidth: '115px',whiteSpace: 'nowrap',textOverflow: 'ellipsis',overflow: 'hidden', wordWrap: 'break-word', wordBreak: 'break-all' }">
            <a-input
              size="small"
              v-if="record.editable"
              :value="text"
              @change="e => handleChange(e.target.value, record.id, 'videoUrl')"/>
            <template v-else>{{ text }}</template>
          </div>
        </span>

        <span slot="armType" slot-scope="text,record">
          <a-select
            v-if="record.editable"
            v-model="text"
            :options="armTypeOptions"
            @select="armTypeSelect(text,record)"
            size="small"
          >
          </a-select>
          <template v-else>
            <span v-if="text==='0'">入口车道</span>
            <span v-if="text==='1'">出口车道</span>
          </template>
        </span>

        <span slot="sourceAreaId" slot-scope="text,record">
          <a-select
            v-if="record.editable"
            v-model="text"
            :options="areaIdOptions"
            @select="sourceAreaIdSelect(text,record)"
            size="small"
          >
          </a-select>
          <template v-else>{{ areaNameTrans(text) }}</template>
        </span>

        <span slot="targetAreaId" slot-scope="text,record">
          <a-select
            v-if="record.editable"
            v-model="text"
            :options="areaIdOptions"
            @select="targetAreaIdSelect(text,record)"
            size="small"
          >
          </a-select>
          <template v-else>{{ areaNameTrans(text) }}</template>
        </span>

        <span slot="armStatus" slot-scope="text,record">
          <a-select
            v-if="record.editable"
            v-model="text"
            :options="armStatusOptions"
            @select="armStatusSelect(text,record)"
            size="small"
          >
          </a-select>
          <template v-else>
            <span v-if="text==='0'">未启用</span>
            <span v-if="text==='1'">启用</span>
          </template>
        </span>

        <template slot="operation" slot-scope="text, record">
          <div class="editable-row-operations">
            <span v-if="record.editable">
              <a @click="() => save(record.id)">保存</a>
              <a-divider type="vertical"></a-divider>
              <a-popconfirm title="确定取消?" okText="确定" cancelText="取消" @confirm="() => cancel(record.id)">
                <a>取消</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a :disabled="editingKey !== ''" @click="() => edit(record.id)">修改</a>
              <a-divider type="vertical"></a-divider>
              <a-popconfirm
                title="确定删除?"
                okText="确定"
                cancelText="取消"
                @confirm="() => del(record.id)">
                <a :disabled="editingKey !== ''">删除</a>
              </a-popconfirm> <!--editingKey !== '' -->
            </span>
          </div>
        </template>
      </a-table>
      <a-row type="flex" justify="center" >
        <a-col :span="12" align="center">
          <a-button style="width:100px" @click="$emit('currentChange',2)">
            下一步
          </a-button>
        </a-col>
      </a-row>
    </div>
  </a-spin>
</template>
<script>
import {
  JeecgListMixin
} from '@/mixins/JeecgListMixin'
import {
  deleteAction,
  putAction,
  getAction,
} from '@/api/manage'
import {
  postAction
} from '../../api/manage';
import {
  filterObj
} from '@/utils/util';

const columns = [

  {
    title: "车道类型",
    dataIndex: "armType",
    width: "113px",
    scopedSlots: {
      customRender: "armType"
    }
  },
  {
    title: "车道名称",
    dataIndex: "armName",
    width: "100px",
    scopedSlots: {
      customRender: "armName"
    }
  },
  {
    title: "源区域",
    dataIndex: "sourceAreaId",
    width: "100px",
    scopedSlots: {
      customRender: "sourceAreaId"
    },
  },
  {
    title: "目标区域",
    dataIndex: "targetAreaId",
    width: "100px",
    scopedSlots: {
      customRender: "targetAreaId"
    }
  },
  {
    title: "设备序列号",
    dataIndex: "serialNo",
    width: "180px",
    scopedSlots: {
      customRender: "serialNo"
    },

  },
  {
    title: "摄像头IP",
    dataIndex: "ipAddr",
    width: "125px",
    scopedSlots: {
      customRender: "ipAddr"
    }
  },
  {
    title: "是否启用",
    dataIndex: "armStatus",
    width: "92px",
    scopedSlots: {
      customRender: "armStatus"
    }
  },
  {
    title: "操作",
    dataIndex: "operation",
    width: "90px",
    scopedSlots: {
      customRender: "operation"
    }
  }
];

const dataSource = [];
// 数组创建时候的下标
var numbe = 0;
export default {
  name: 'ParkArmInfoDeployModel',
  mixins: [JeecgListMixin],
  data() {
    this.cacheData = dataSource.map(item => ({
      ...item
    }));
    return {
      loading: false,
      dataSource,
      columns,
      ipagination: {
        current: 1,
        pageSize: 4,
        // pageSizeOptions: ['10', '20', '30'],
        pageSizeOptions: ['4'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      selectValue: [],
      editingKey: "",
      form: this.$form.createForm(this),
      selectedRowKeys: [],
      queryParam: {
        "opTime_begin": "",
        "opTime_end": "",
        "type": "-1",
      },
      url: {
        list: "/parking/parkArmInfo/list",
        add: "/parking/parkArmInfo/add",
        edit: "/parking/parkArmInfo/edit",
        delete: "/parking/parkArmInfo/delete",
        areaList:"/area/parkAreaInfo/getAreaInfos"
      },
      labelCol: {
        xs: {span: 8},
        sm: {span: 8},
        style: 'textAlign: left',
      },
      wrapperCol: {
        xs: {span: 14},
        sm: {span: 14},
        style: 'textAlign: right'
      },
      armTypeOptions: [
        {value: "0", label: '入口车道'},
        {value: "1", label: '出口车道'}],
      armStatusOptions: [
        {value: "0", label: '未启用'},
        {value: "1", label: '启用'}
      ],
      areaIdOptions:[
        {value:"",label:'不启用'}
      ],
      OldRecords: [],
      NewRecords: [],

    };


  },
  props: ['parkInfo'],
  mounted() {

    /*this.loadData()*/
    this.keyupEnter()
  },
  created() {

  },
  methods: {

    keyupEnter() {
      document.onkeydown = e => {
        let body = document.getElementsByTagName('body')[0]
        if (e.keyCode === 13) {
          this.loadData(1);
        }
      }
    },


    getQueryParams() {
      var param = Object.assign({}, this.isorter, this.queryParam);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;

      // delete param.createTimeRange; // 时间参数不传递后台
      return filterObj(param);
    },
    async loadData(arg) {
      this.editingKey = ''
      this.loading = true;
      //判断当前页面，是否设置url属性
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams(); //查询条件
      params.parkCode = this.parkInfo.parkCode;
      await this.loadAreaList();

      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records;
          this.ipagination.total = res.result.total;

        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false;
      })
    },
    async loadAreaList(){
      const that = this
      if(!this.url.areaList)
      {
        this.$message.error("请设置this.url.areaList属性!")
        return
      }
      this.loading=true
      let params = {}
      params.parkCode = this.parkInfo.parkCode
      await getAction(this.url.areaList,params).then(res=>{
        if(res.success){
          that.areaIdOptions = [{value:"",label:'不启用'}]
          res.result.forEach(area=>{
            that.areaIdOptions.push({
              value:area.id,
              label:area.areaName
            })
          })
        }else {
          this.$message.error(res.message);
        }
        that.loading = false
      })
    },
    onSubmit() {
      const that = this;
      this.form.validateFields((err, values) => {
        values.parkCode = this.parkInfo.parkCode
        values.parkName = this.parkInfo.parkName
        values.serialNo = values.serialNo.trim()
        if (!err) {
          this.loading = true
          postAction(this.url.add, values).then((res) => {
            if (res.success) {
              that.loadData();
              that.$message.success(res.message);
              that.form.resetFields();
            } else {
              that.$message.error(res.message);
            }
          }).finally(() => {
            this.loading = false;
          })

        }
      })


    },
    handleChange(value, key, column) {

      const newData = [...this.dataSource];
      const target = newData.filter(item => key === item.id)[0];
      if (target) {
        target[column] = value;
        this.dataSource = newData;
        this.NewRecords = target
      }
    },
    del(id) {
      const newData = [...this.dataSource];
      deleteAction(this.url.delete, {
        invateuserdetailId: id
      }).then((res => {
        if (res.success) {
          var index = newData.findIndex(function (item) {
            return item.id == id;
          })
          newData.splice(index, 1);
          this.$message.success('删除成功')
          this.loadData();
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
      }))
    },
    edit(id) {
      const newData = [...this.dataSource];
      const target = newData.filter(item => id === item.id)[0];
      this.OldRecords = Object.assign(target)
      this.editingKey = id;
      if (target) {
        target.editable = true;
        this.dataSource = newData;
      }
    },
    save(id) {
      const that = this
      const newData = [...this.dataSource];
      const newCacheData = [...this.cacheData];
      const target = newData.filter(item => id === item.id)[0];
      this.loading = true
      putAction(this.url.edit, {
        id: target.id,
        armStatus: target.armStatus,
        armType: target.armType,
        armName: target.armName,
        serialNo: target.serialNo,
        ipAddr: target.ipAddr,
        targetAreaId:this.NewRecords.targetAreaId,
        sourceAreaId:this.NewRecords.sourceAreaId
      }).then((res) => {
        if (res.success) {
          delete target.editable;
          this.editingKey = "";
          this.dataSource = newData;
          this.$message.success(res.message)
        } else {
          this.$message.warning(res.message)
        }
        that.loading = false
      })
    },
    cancel(id) {
      const newData = [...this.dataSource];
      const target = newData.filter(item => id === item.id)[0];
      this.editingKey = "";
      if (target) {
        Object.assign(
            target,
            this.cacheData.filter(item => id === item.id)[0]
        );
        delete target.editable;
        this.dataSource = newData;
      }
      this.loadData()
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    armTypeSelect(text, record) {
      record.armType = text
      this.NewRecords = Object.assign(record)
    },
    armStatusSelect(text, record) {
      record.armStatus = text
      this.NewRecords = Object.assign(record)
    },
    sourceAreaIdSelect(text,record){
      record.sourceAreaId = text
      this.NewRecords = Object.assign(record)
    },
    targetAreaIdSelect(text,record){
      record.targetAreaId = text
      this.NewRecords = Object.assign(record)
    },
    areaNameTrans(text){
      let returnStr = ""
      this.areaIdOptions.forEach(area=>{
        if(text===area.value)
        {
          returnStr = area.label
        }
      })
      return returnStr
    },

  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    }
  },
  watch: {
    parkInfo() {
      this.loadData()
    }
  },
};
</script>
<style scoped>
/deep/ .ant-table-middle > .ant-table-content > .ant-table-body > table > .ant-table-tbody > tr > td {
  height: 50px;
}

/deep/ .ant-form-inline .ant-form-item {
  display: inline-block;
  margin-right: 0px;
  margin-bottom: 0;
}

/deep/ .ant-table-header-column {
  width: 100%;
  text-align: center;
}

/deep/ .ant-table-tbody {
  text-align: center;
}
</style>
